package com.activity.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.activity.App;
import com.activity.ImageActivity;
import com.activity.Person1Activity;
import com.activity.PersonActivity;
import com.activity.PersonInfoActivity;
import com.activity.SettingActivity;
import com.activity.bean.UserBean;
import com.activity.shop.ShopMangerActivity;
import com.api.param.LoginParam;
import com.api.param.UpdateUserParam;
import com.api.viewModel.LoginVM;
import com.baoyz.actionsheet.ActionSheet;
import com.example.apple.ddhr_new.R;
import com.example.apple.ddhr_new.activity.widget.BLinearLayout;
import com.example.apple.ddhr_new.activity.widget.MyScrollView;
import com.example.apple.ddhr_new.utils.ActivityUtil;
import com.example.apple.ddhr_new.utils.ImageViewUtil;
import com.example.apple.ddhr_new.utils.ScreenUtil;
import com.example.apple.ddhr_new.utils.ToastUtil;
import com.example.lzbase.BaseActivity;
import com.example.lzbase.BaseViewModelFragment;
import com.gyf.barlibrary.ImmersionBar;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.SimpleMultiPurposeListener;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import event.MessageEvent;

import static android.app.Activity.RESULT_OK;

public class HomeFragment extends BaseViewModelFragment<LoginVM> {
    @BindView(R.id.icon)
    ImageView icon;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.tv_group_name)
    TextView tvGroupName;
    @BindView(R.id.l_margin)
    LinearLayout lMargin;
    @BindView(R.id.tv_vip)
    TextView tvVip;
    @BindView(R.id.recycle_view)
    MyScrollView recycleView;
    @BindView(R.id.nav_bar)
    LinearLayout navBar;
    @BindView(R.id.nav_title)
    TextView navTitle;
    @BindView(R.id.parallax)
    ImageView parallax;
    @BindView(R.id.btn_zhuye)
    LinearLayout btnZhuye;
    @BindView(R.id.l_shangjia)
    LinearLayout lShangjia;
    @BindView(R.id.l_guge)
    LinearLayout lGuge;
    @BindView(R.id.qie_huan)
    ImageView qieHuan;
    @BindView(R.id.l_dianpu)
    LinearLayout lDianpu;
    @BindView(R.id.status_view)
    View statusView;
    @BindView(R.id.iv_shizhi)
    ImageView ivShizhi;
    private int mOffset;
    private int mScrollY;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_home1;
    }

    @Override
    public void initStatusBar() {
        ImmersionBar.with(this)
                .titleBar(rootView.findViewById(R.id.nav_bar))
                .statusBarDarkFont(true)
                .flymeOSStatusBarFontColor(R.color.black)
                .init();
    }

    @OnClick(R.id.btn_zhuye)
    public void onViewClicked() {
        ActivityUtil.startActivity(mContext, Person1Activity.class);
    }

    @OnClick(R.id.iv_shizhi)
    public void setClicked() {

        ActivityUtil.startActivity(mContext, SettingActivity.class);
    }

    @OnClick(R.id.l_shop)
    public void shopClicked() {
        if (App.getInstance().getAccount().getUserstoreinfo() != null && App.getInstance().getAccount().getUserstoreinfo().size() > 0) {
            ActivityUtil.startActivity(mContext, ShopMangerActivity.class);
        } else {
            ToastUtil.toast(mContext, "没有关联您的店铺信息");
        }


    }

    @OnClick(R.id.iv_saoma)
    public void saomaClicked() {
        Intent intent = new Intent(mContext, CaptureActivity.class);
        startActivityForResult(intent, 1000);

    }

    @OnClick(R.id.iv_erweima)
    public void erweimaClicked() {
        Bundle bundle = new Bundle();
        bundle.putString("name", "二维码");
        bundle.putString("image", "erweima.png");
        bundle.putFloat("width", 1242.0f);
        bundle.putFloat("height", 1944.0f);
        ActivityUtil.startActivity(mContext, ImageActivity.class, bundle);


    }

    @Override
    public void createView() {
        super.createView();
        updateIcon();
        navBar.getBackground().setAlpha(0);
        navTitle.setAlpha(0);
        refreshLayout.setEnableLoadMore(false);


        List<UserBean.UserstoreinfoBean> stores = App.getInstance().getAccount().getUserstoreinfo();
        if (stores != null && stores.size() > 0) {

            tvGroupName.setText(stores.get(0).getStorename());
            App.getInstance().userstoreinfoBean = stores.get(0);

        } else {
            tvGroupName.setText("");

        }


        recycleView.setOnScrollListener(new MyScrollView.OnScrollListener() {
            private int lastScrollY;
            private int h = ScreenUtil.dp2px(mContext, 180 - 44) - ImmersionBar.getStatusBarHeight((Activity) mContext);

            @Override
            public void onScroll(int scrollY1) {
                lastScrollY = scrollY1;


                if (lastScrollY > h) {
                    navBar.getBackground().setAlpha(255);
                    navTitle.setAlpha(1);
                } else {
                    navBar.getBackground().setAlpha(0);
                    navTitle.setAlpha(0);

                }


                if (lastScrollY < 0) {
                    lastScrollY = 0;
                }
                if (lastScrollY < h) {
                    int scrollY = Math.min(h, lastScrollY);
                    mScrollY = scrollY > h ? h : scrollY;
//                    buttonBar.setAlpha(1f * mScrollY / h);

                    parallax.setTranslationY(mOffset - mScrollY);
                }
            }
        });

//        recycleView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
//            private int lastScrollY = 0;
//            private int h = ScreenUtil.dp2px(mContext, 180 -44) - ImmersionBar.getStatusBarHeight((Activity) mContext);
//
//            @Override
//            public void onScrollChange(View v, int scrollX, int scrollY1, int oldScrollX, int oldScrollY) {
//
//
//
//
//            }
//        });
        refreshLayout.setOnMultiPurposeListener(new SimpleMultiPurposeListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                addSubscription(viewModel.getPersonInfo(new LoginParam(App.getInstance().getAccount().getUsername(), "")));

            }

            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {


            }

            @Override
            public void onHeaderMoving(RefreshHeader header, boolean isDragging, float percent, int offset, int headerHeight, int maxDragHeight) {
                mOffset = offset;
                int bz = 0;
                if (Math.abs(mOffset) > ScreenUtil.dp2px(mContext, 50)) {
                    bz = ScreenUtil.dp2px(mContext, 50);
                } else {
                    bz = Math.abs(mOffset);
                }
                float p = 1 - ((float) bz / (float) ScreenUtil.dp2px(mContext, 50));


                if (recycleView.getChildAt(0).findViewById(R.id.l_bz) != null) {
                    ((BLinearLayout) recycleView.getChildAt(0).findViewById(R.id.l_bz)).setPercent(p);
                }


                parallax.setTranslationY(mOffset - mScrollY);

            }

            @Override
            public void onFooterMoving(RefreshFooter footer, boolean isDragging, float percent, int offset, int footerHeight, int maxDragHeight) {

                if (mScrollY == 0)
                    parallax.setTranslationY(-offset - mScrollY);

            }
            //            @Override
//            public void onHeaderPulling(@NonNull RefreshHeader header, float percent, int offset, int bottomHeight, int maxDragHeight) {
//                mOffset = offset / 2;
//                parallax.setTranslationY(mOffset - mScrollY);
//                toolbar.setAlpha(1 - Math.min(percent, 1));
//            }
//            @Override
//            public void onHeaderReleasing(@NonNull RefreshHeader header, float percent, int offset, int bottomHeight, int maxDragHeight) {
//                mOffset = offset / 2;
//                parallax.setTranslationY(mOffset - mScrollY);
//                toolbar.setAlpha(1 - Math.min(percent, 1));
//            }
        });

        addSubscription(viewModel.getPersonInfo(new LoginParam(App.getInstance().getAccount().getUsername(), "")));

    }

    @OnClick(R.id.iv_edit)
    public void editClick() {
        ActivityUtil.startActivity(mContext, PersonInfoActivity.class);
    }

    @Override
    public void onError(Throwable error) {
        super.onError(error);
        refreshLayout.finishRefresh();
    }

    @OnClick(R.id.icon)
    public void onClick() {


        ActionSheet.createBuilder(mContext, ((BaseActivity) mContext).getSupportFragmentManager())
                .setCancelButtonTitle(mContext.getString(R.string.cacel))
                .setOtherButtonTitles(mContext.getString(R.string.camera), mContext.getString(R.string.take_photo))
                .setCancelableOnTouchOutside(true)
                .setListener(new ActionSheet.ActionSheetListener() {
                    @Override
                    public void onDismiss(ActionSheet actionSheet, boolean isCancel) {

                    }

                    @Override
                    public void onOtherButtonClick(ActionSheet actionSheet, int index) {

                        if (index == 0) {
                            PictureSelector.create(HomeFragment.this)
                                    .openCamera(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()

                                    .maxSelectNum(1)// 最大图片选择数量 int
                                    .imageSpanCount(4)// 每行显示个数 int
                                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                                    .previewImage(true)// 是否可预览图片 true or false
                                    .previewVideo(true)// 是否可预览视频 true or false
                                    .enablePreviewAudio(true) // 是否可播放音频 true or false
                                    .isCamera(true)// 是否显示拍照按钮 true or false
                                    .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                                    .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                                    .enableCrop(true)
                                    .showCropGrid(false)
                                    .withAspectRatio(1, 1).compress(true)// 是否压缩 true or false
                                    .isGif(false)// 是否显示gif图片 true or false
                                    .openClickSound(false)// 是否开启点击声音 true or false
                                    .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                                    .synOrAsy(true)//同步true或异步false 压缩 默认同步
                                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                        } else {
                            PictureSelector.create(HomeFragment.this)
                                    .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()

                                    .maxSelectNum(1)// 最大图片选择数量 int
                                    .imageSpanCount(4)// 每行显示个数 int
                                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                                    .previewImage(true)// 是否可预览图片 true or false
                                    .previewVideo(true)// 是否可预览视频 true or false
                                    .enablePreviewAudio(true) // 是否可播放音频 true or false
                                    .isCamera(true)// 是否显示拍照按钮 true or false
                                    .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                                    .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                                    .enableCrop(true)
                                    .showCropGrid(false)
                                    .withAspectRatio(1, 1).compress(true)// 是否压缩 true or false
                                    .isGif(false)// 是否显示gif图片 true or false
                                    .openClickSound(false)// 是否开启点击声音 true or false
                                    .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                                    .synOrAsy(true)//同步true或异步false 压缩 默认同步
                                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                        }
                    }
                }).show();
    }

    @Override
    public void onMessageEventBus(MessageEvent event) {
        super.onMessageEventBus(event);
        if (event.getMessage() == MessageEvent.MESSAGE_EVENT_UPDATE_USER) {


            updateIcon();


        }
    }

    private void updateIcon() {
        UserBean userBean = App.getInstance().getAccount();

        ImageViewUtil.loadCircleImage(userBean.getUsericon(), icon, mContext);
        tvName.setText(userBean.getUsernickname());
        navTitle.setText(userBean.getUsernickname());
        if (userBean.getUsercertificated().equals("1")) {

            tvVip.setText("已认证");
        } else {
            tvVip.setText("未认证");
        }
        refreshLayout.finishRefresh();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);


                    ArrayList<String> arrayList = new ArrayList<>();
                    for (int i = 0; i < selectList.size(); i++) {
                        LocalMedia media = selectList.get(i);
                        String path = media.getCompressPath();

                        arrayList.add(path);

                    }

                    viewModel.uplaodImages(arrayList, new LoginVM.ImageResult() {
                        @Override
                        public void result(ArrayList<String> result, ArrayList<String> origin) {
                            if (result.size() == 0)
                                return;

                            String imgurl = result.get(0);

                            UpdateUserParam param = new UpdateUserParam();
                            UserBean userBean = App.getInstance().getAccount();
                            param.usericon = imgurl;
                            param.usernickname = userBean.getUsernickname();
                            param.userbirthday = userBean.getUserbirthday();
                            param.userprovince = userBean.getUserprovince();
                            param.usercity = userBean.getUsercity();
                            param.usersex = userBean.getUsersex();
                            param.userrealname = userBean.getUserrealname();
                            param.userbrief = userBean.getUserbrief();
                            param.userrank = userBean.getUserrank();
                            param.useremail = userBean.getUseremail();
                            param.useraddress = userBean.getUseraddress();
                            param.usercompany = userBean.getUsercompany();
                            param.userbackground = userBean.getUserbackground();
                            param.userfacecertificated = userBean.getUserfacecertificated();
                            param.usertel = userBean.getUsertel();
                            addSubscription(viewModel.updateUserinfo(param));
                        }
                    }, "usericon");
//                    picture.reload();

                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的

                    break;
            }
        }
        if (requestCode == 1000) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    ToastUtil.toast(mContext, "解析结果:" + result);
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {

                    ToastUtil.toast(mContext, "解析二维码失败:");
                }
            }
        }
    }

    @OnClick(R.id.qie_huan)
    public void qihuanClick() {

        if (App.getInstance().getAccount().getUserprofessioncertificated().equals("1")) {

            if (qieHuan.isSelected()) {
                qieHuan.setImageResource(R.drawable.qiehuanshangjia);
                lGuge.setVisibility(View.VISIBLE);
                lShangjia.setVisibility(View.GONE);
                lDianpu.setBackgroundResource(R.drawable.shape_dianpu_lan_corner);

            } else {
                lGuge.setVisibility(View.GONE);
                lShangjia.setVisibility(View.VISIBLE);
                qieHuan.setImageResource(R.drawable.qie_huan_gu_ke);
                lDianpu.setBackgroundResource(R.drawable.shape_dianpu_huang_corner);
            }

            qieHuan.setSelected(!qieHuan.isSelected());

        } else {

            ToastUtil.toast(mContext, "您还未认证通过,无法切换商家");
        }
    }

    @OnClick(R.id.l_dianpu)
    public void dianpuClick() {


        List<UserBean.UserstoreinfoBean> stores = App.getInstance().getAccount().getUserstoreinfo();
        if (stores != null && stores.size() > 0) {


            Bundle bundle = new Bundle();
            bundle.putString("name", tvGroupName.getText().toString());
            bundle.putString("image", "dianpu.png");
            bundle.putFloat("width", 1242.0f);
            bundle.putFloat("height", 3694.0f);
            ActivityUtil.startActivity(mContext, ImageActivity.class, bundle);

        } else {
            tvGroupName.setText("");
            ToastUtil.toast(mContext, "暂无店铺信息");

        }

    }


    @OnClick({R.id.l_dianpu_huiyuanka, R.id.l_guge_huiyuanka})
    public void huiyuankaClick(View view) {
        Bundle bundle = new Bundle();
        bundle.putString("name", "我的会员卡");
        bundle.putString("image", "huiyuanka.png");
        bundle.putFloat("width", 1242.0f);
        bundle.putFloat("height", 2414.0f);
        ActivityUtil.startActivity(mContext, ImageActivity.class, bundle);
    }
    @OnClick({R.id.l_guge_quan, R.id.l_shangjia_quan})
    public void quanClick(View view) {
        Bundle bundle = new Bundle();
        bundle.putString("name", "我的券包");
        bundle.putString("image", "quanbao.png");
        bundle.putFloat("width", 750);
        bundle.putFloat("height", 1334.0f);
        ActivityUtil.startActivity(mContext, ImageActivity.class, bundle);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden == false) {

            addSubscription(viewModel.getPersonInfo(new LoginParam(App.getInstance().getAccount().getUsername(), "")));

        }
    }
    @Override
    public void onResume() {
        super.onResume();

        if (isHidden()) {

        } else {
            addSubscription(viewModel.getPersonInfo(new LoginParam(App.getInstance().getAccount().getUsername(), "")));

        }


    }
}
